import { login, queryUserInfo } from '@/services/user';
import {history} from 'umi'
  
  export default {
    namespace: 'common',
    state: {
      token: '',
      userInfo: {},
      // userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : { accountname: 'admin' }
    },
    effects: {
      *goLogin({ payload }, { call, put }) {
        const response = yield call(login, payload);
        yield put({
          type: 'saveToken',
          payload: response.data.token,
        });
        return response
      },
      *getUserInfo({}, { call, put }) {
        const response = yield call(queryUserInfo);
        localStorage.setItem('userInfo', JSON.stringify(response?.data??{}))
        yield put({
          type: 'getUser',
          payload: response?.data??{},
        });
        return response
      },
      *loginout({}, {call, put}) {
        localStorage.removeItem('token_umi_app')
        localStorage.removeItem('userInfo')
        history.push('/login')
        yield put({
          type: 'setLoginOut',
        });
      }
    },
    reducers: {
      saveToken(state, action) {
          return { ...state, token: action.payload || '' }
      },
      getUser(state, action) {
        return { ...state, userInfo: action.payload || {} };
      },
      setLoginOut(state, action){
        return { ...state, token: '', userInfo: {} };
      }
    },
  };
  